package com.nanhang.controller;

import com.nanhang.booksearch.BookIS0;
import com.nanhang.booksearch.BookS0;
import com.nanhang.entity.Bookborrow;
import com.nanhang.entity.Bookinfo;
import com.nanhang.service.IBookinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import util.PageResult;
import util.R;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ymm
 * @since 2025-01-09
 */
@RestController
@RequestMapping("/bookinfo")
public class BookinfoController {

    @Autowired
    private IBookinfoService bookinfoService;

    @GetMapping("/list")
    public R findAllCLASS(){
        List<Bookinfo> list = bookinfoService.list();
        return R.ok().data("books",list);
    }

    @PostMapping("/search/{page}/{pagesize}")
    public R search(@PathVariable("page") Integer page,
                    @PathVariable("pagesize") Integer pagesize,
                    @RequestBody(required = false) BookIS0 BS0) {
        PageResult<Bookinfo> res = bookinfoService.search(page, pagesize, BS0);
        return R.ok().data("res", res);
    }

    @DeleteMapping("/delete/{dbid}")
    public R delete(@PathVariable("dbid") String dbid){
        String[] split = dbid.split(",");
        List<String> dbids = Arrays.asList(split);
        for (String string : dbids) {
            int s = Integer.valueOf(string);
            Bookinfo bi = bookinfoService.getById(s);
            String binfo = bi.getStatus();
            if (Objects.equals(binfo, "借出")){
                return R.error().message("无法删除已经借出的书籍！");
            }
        }
        return bookinfoService.removeByIds(dbids) ? R.ok().message("删除成功"):R.error().message("删除失败！");
    }
}
